package cn.caplike.demo.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.nio.charset.StandardCharsets;

/**
 * @author LiKe
 * @version 1.0.0
 * @date 2022-11-17 12:39
 */
public class ByteBufTest1 {

    public static void main(String[] args) {
        final ByteBuf byteBuf = Unpooled.copiedBuffer("张hello world", StandardCharsets.UTF_8 /*中文3字节,英文1字节*/);
        if (byteBuf.hasArray()) {
            final byte[] content = byteBuf.array();
            System.out.println(new String(content, StandardCharsets.UTF_8));
            System.out.println(byteBuf); // cap: 33 ? -> io.netty.buffer.ByteBufUtil.encodeString0

            System.out.println(byteBuf.arrayOffset());
            System.out.println(byteBuf.readerIndex());
            System.out.println(byteBuf.writerIndex());
            System.out.println(byteBuf.capacity());

            final int readableBytes = byteBuf.readableBytes(); // = writerIdx - readerIdx
            System.out.println(readableBytes);

            for (int i = 0; i < readableBytes; i++) {
                System.out.println((char) byteBuf.getByte(i));
            }

            System.out.println(byteBuf.getCharSequence(0, 3, StandardCharsets.UTF_8));
            System.out.println(byteBuf.getCharSequence(4, 6, StandardCharsets.UTF_8));
        }
    }
}
